package demo.hdz.testopengl;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.ActivityManager;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ConfigurationInfo;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.opengl.GLSurfaceView;
import android.os.Build;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.Toast;

import java.util.ArrayList;
import java.util.List;

/**
 * @author hdz
 * @date 2018/07/26
 */
public class MainActivity extends AppCompatActivity {

    private static final int PERMISSION_REQUEST_CODE          = 1000;
    private static final int PERMISSION_REQUEST_CODE_STORAGE  = 1001;
    private static final int PERMISSION_REQUEST_CODE_RECORD   = 1002;

    private GLSurfaceView mGlSurfaceView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        askForPermission();
        if (!isSupportGL()) {
            Toast.makeText(MainActivity.this, "不支持OpenGL", Toast.LENGTH_SHORT).show();
            setContentView(R.layout.activity_main);
        } else {
            mGlSurfaceView = new GLSurfaceView(this);
            mGlSurfaceView.setRenderer(new GLRenderer());
            setContentView(mGlSurfaceView);
        }
    }

    private boolean isSupportGL() {
        ActivityManager activityManager = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
        ConfigurationInfo configurationInfo = activityManager.getDeviceConfigurationInfo();

        int glVer = configurationInfo.reqGlEsVersion;
        Logger.i("OpenGL Version: 0x" + String.format("%x", glVer));

        boolean supportsEs2 = glVer >= 0x2000;

        boolean isEmulator = Build.VERSION.SDK_INT > Build.VERSION_CODES.ICE_CREAM_SANDWICH_MR1
                && (Build.FINGERPRINT.startsWith("generic")
                || Build.FINGERPRINT.startsWith("unknown")
                || Build.MODEL.contains("google_sdk")
                || Build.MODEL.contains("Emulator")
                || Build.MODEL.contains("Android SDK built for x86"));

        supportsEs2 = supportsEs2 || isEmulator;

        return supportsEs2;
    }




    private void askForPermission(){
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            List<String> permissionList = new ArrayList<>();
            if (ContextCompat.checkSelfPermission(this, android.Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                permissionList.add(Manifest.permission.WRITE_EXTERNAL_STORAGE);
            }
            if (ContextCompat.checkSelfPermission(this, android.Manifest.permission.RECORD_AUDIO) != PackageManager.PERMISSION_GRANTED) {
                permissionList.add(Manifest.permission.RECORD_AUDIO);
            }
            if (permissionList.size() > 0) {
                //将List转为数组
                String[] permissions = permissionList.toArray(new String[permissionList.size()]);
                ActivityCompat.requestPermissions(this, permissions, PERMISSION_REQUEST_CODE);
            }
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        if (requestCode == PERMISSION_REQUEST_CODE_STORAGE) {
            if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                showToast("文件读写权限已开启");
            } else {
                showToast("文件读写权限已拒绝");
            }
//        } else if (requestCode == PERMISSION_REQUEST_CODE_RECORD) {
//            if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
//                showToast("录音权限已开启");
//            } else {
//                showToast("录音权限已拒绝");
//            }
        } else if (requestCode == PERMISSION_REQUEST_CODE){
            String sToast = "";
            for (int i = 0; i < grantResults.length; i++) {
                if (grantResults[i] != PackageManager.PERMISSION_GRANTED) {
                    boolean showRequestPermission = ActivityCompat.shouldShowRequestPermissionRationale(MainActivity.this, permissions[i]);
                    if (showRequestPermission) {
                        //禁止后但没有勾选不再询问
                        if (permissions[i].equals(Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
                            if (!sToast.equals("")) {
                                sToast += "、";
                            }
                            sToast += "文件读写权限";
//                        } else if (permissions[i].equals(Manifest.permission.RECORD_AUDIO)) {
//                            if (!sToast.equals("")) {
//                                sToast += "、";
//                            }
//                            sToast += "录音权限";
                        }
                    } else {
                        //勾选不再询问并禁止
                        if (permissions[i].equals(Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
                            if (!sToast.equals("")) {
                                sToast += "、";
                            }
                            sToast += "文件读写权限";
//                        } else if (permissions[i].equals(Manifest.permission.RECORD_AUDIO)) {
//                            if (!sToast.equals("")) {
//                                sToast += "、";
//                            }
//                            sToast += "录音权限";
                        }
                    }
                }
            }
            if (!sToast.equals("")) {
                showToast("请开启"+sToast);
                //转到系统设置中的应用设置界面
                goAppSettings(this);
            }
        }
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }
    @SuppressLint("ObsoleteSdkInt")
    private void goAppSettings(Context context){
        Intent intent = new Intent();
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.GINGERBREAD){
            intent.setAction("android.settings.APPLICATION_DETAILS_SETTINGS");
            intent.setData(Uri.fromParts("package", getPackageName(), null));
        } else if(Build.VERSION.SDK_INT <= Build.VERSION_CODES.FROYO){
            intent.setAction(Intent.ACTION_VIEW);
            intent.setClassName("com.android.settings","com.android.settings.InstalledAppDetails");
            intent.putExtra("com.android.settings.ApplicationPkgName", getPackageName());
        }
        context.startActivity(intent);
    }


    private void showToast(String msg) {
        Toast.makeText(MainActivity.this, msg, Toast.LENGTH_SHORT).show();
    }




    @Override
    protected void onStart() {
        super.onStart();
        Logger.d("==onStart==");
    }

    @Override
    protected void onResume() {
        super.onResume();
        Logger.d("==onResume==");
        if (mGlSurfaceView != null) {
            mGlSurfaceView.onResume();
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        if (mGlSurfaceView != null) {
            mGlSurfaceView.onPause();
        }
    }

    @Override
    protected void onStop() {
        super.onStop();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }
}
